import 'package:cmd_myapp_demo/components/my_app.dart';
import 'package:cmd_myapp_demo/components/my_home_page.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp(child: _AnimateBuilderDemo()));
}

class _AnimateBuilderDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MyHomePage(
      title: const Text("AnimationBuilder"),
      child: _AnimatedBuilderPage(),
    );
  }
}

class _AnimatedBuilderPage extends StatefulWidget{
  @override
  _AnimatedBuilderPageState createState() => _AnimatedBuilderPageState();
}

class _AnimatedBuilderPageState extends State<_AnimatedBuilderPage> with SingleTickerProviderStateMixin{

  late final Animation<double> animation;
  late final AnimationController controller;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      duration: const Duration(milliseconds: 2000),
      vsync: this
    );

    final CurvedAnimation curve = CurvedAnimation(parent: controller, curve: Curves.bounceIn);

    animation = Tween(begin: 10.0, end: 300.0).animate(curve)..addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        controller.reverse();
      } else if (status == AnimationStatus.dismissed) {
        controller.forward();
      }
    });

    controller.forward();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _GrowTransition(animation: animation, child: _LogoWidget());
  }
}

class _LogoWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 10.0),
      child: const FlutterLogo(),
    );
  }
}

class _GrowTransition extends StatelessWidget {

  const _GrowTransition({required this.child, required this.animation});

  final Widget child;
  final Animation<double> animation;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: AnimatedBuilder(
        animation: animation,
        builder: (context, child) {
          return SizedBox(
              width: animation.value,
              height: animation.value,
              // 这里的 child 是由 AnimatedBuilder 给匿名类的
              child: child
          );
        },
        // 这里的 child 是传递给 AnimatedBuilder 的
        child: child,
      ),
    );
  }
}